<?php

namespace backend\modules\sys\controllers;
use yii;
use yii\web\Controller;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\Settings;
use backend\models\ActionLog;
use c006\alerts\Alerts;

class SettingsController extends BaseController
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    protected function findModel($organization_id)
    {
        if (($model = Settings::find()->where(['organization_id'=>$organization_id])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionBackend()
    {
        $model = $this->findModel(Yii::$app->user->identity->organization_id);
        if(Yii::$app->request->isPost)
        {
            $enable_modules_arr = \Yii::$app->request->post()['Settings']['enable_modules'];
            $enable_modules_arr = !empty($enable_modules_arr) ? $enable_modules_arr : [];
            $enable_modules_ids = implode(',',$enable_modules_arr);
            $model->enable_modules = $enable_modules_ids;
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                Yii::$app->system->writeLog();
                Alerts::setMessage('配置更新成功!');
                Alerts::setAlertType(Alerts::ALERT_SUCCESS);
            }
        }

        $enable_modules_ids = Yii::$app->settings->get('enable_modules');
        //$enable_modules_ids = !empty($enable_modules_ids) ? $enable_modules_ids : 0;
        $model->enable_modules = explode(',',$enable_modules_ids);
        return $this->render('backend', [
            'model' => $model,
        ]);
    }

}
